package com.changgou.good.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.good.dao.BrandMapper;
import com.changgou.good.dao.CategoryMapper;
import com.changgou.good.dao.SkuMapper;
import com.changgou.good.dao.SpuMapper;
import com.changgou.good.service.SpuService;
import com.changgou.goods.pojo.*;
import entity.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.util.StringUtil;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class SpuServiceImpl implements SpuService {

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private SpuMapper spuMapper;

    @Override
    public void saveGoods(Goods goods) {
        Spu spu = goods.getSpu();
        spu.setId(idWorker.nextId());
        spuMapper.insertSelective(spu);

        // sku
        Date date = new Date();
        Category category = categoryMapper.selectByPrimaryKey(spu.getCategory3Id());
        Brand brand = brandMapper.selectByPrimaryKey(spu.getBrandId());
        List<Sku> skuList = goods.getSkuList();
        for (Sku sku : skuList){
            if (StringUtil.isEmpty(sku.getSpec())){
                sku.setSpec("{}");
            }
            String name = spu.getName();
            Map<String, String> specMap = JSON.parseObject(sku.getSpec(), Map.class);
            for (Map.Entry<String, String> entity : specMap.entrySet()){
                name += " " + entity.getValue();
            }
            // name
            sku.setName(name);
            sku.setId(idWorker.nextId());
            sku.setBrandName(brand.getName());
            sku.setSpuId(spu.getId());
            sku.setCreateTime(date);
            sku.setUpdateTime(date);
            sku.setCategoryId(category.getId());
            sku.setCategoryName(category.getName());
            skuMapper.insertSelective(sku);
        }
    }
}
